<template>
    <div>
        <a-table bordered :dataSource="dataSource" :columns="columns" :scroll="{ x:1700 }" :pagination="false">

            <template slot="test" slot-scope="text, record">
                <div>
                    <span v-if="dataSource.length <= 1">
                        <a-icon type="plus" @click="handleAdd"/>
                    </span>
                    <span v-else>
                        <a-icon type="plus" @click="handleAdd"/>
                        <a-icon type="minus" @click="() => onDelete(record.key)"/>
                    </span>
                </div>
            </template>

            <!--            物品编号 itemNumber-->
            <template slot="itemNumber" slot-scope="text, record">
                <editable-cell
                        :ref="`itemNumber_${record.key}`"
                        :defaultEditable="record.editable"
                        :autoSave=true
                        :required="false"
                        placeholder='物品编号'
                        :value="text"
                        :text="text"
                        @valueChange="onCellChange(record.key, 'itemNumber', $event)"/>
            </template>

            <!--                        物品名称 itemName-->
            <template slot="itemName" slot-scope="text, record">
                <editable-cell
                        :ref="`itemName_${record.key}`"
                        :defaultEditable="record.editable"
                        :autoSave=true
                        :required="true"
                        :decoratorOptions="rules.itemName"
                        placeholder='物品名称'
                        :value="text"
                        :text="text"
                        @valueChange="onCellChange(record.key, 'itemName', $event)"/>
            </template>

            <!--                        规格型号 model-->
            <template slot="model" slot-scope="text, record">
                <editable-cell
                        :ref="`model_${record.key}`"
                        :defaultEditable="record.editable"
                        :autoSave=true
                        :required="false"
                        :value="text"
                        :text="text"
                        @valueChange="onCellChange(record.key, 'model', $event)"/>
            </template>

            <!--                        单位 unit-->
            <template slot="unit" slot-scope="text, record">
                <editable-cell :ref="`unit_${record.key}`"
                               formType="select"
                               :defaultEditable="record.editable"
                               :required="true"
                               :value="record.unit"
                               :text="record.unit"
                               @valueChange="onCellChange(record.key, 'unit', $event)">
                    <a-select-option value="test1">
                        test1
                    </a-select-option>
                    <a-select-option value="test2">
                        test2
                    </a-select-option>
                </editable-cell>
            </template>

            <!--                        采购数量 amount-->
            <template slot="amount" slot-scope="text, record">
                <editable-cell
                        :ref="`amount_${record.key}`"
                        :defaultEditable="record.editable"
                        :autoSave=true
                        :required="false"
                        :value="text"
                        :text="text"
                        @valueChange="onCellChange(record.key, 'amount', $event)"/>
            </template>

            <!--                        含税单价 unitPrice-->
            <template slot="unitPrice" slot-scope="text, record">
                <editable-cell
                        :ref="`unitPrice_${record.key}`"
                        :defaultEditable="record.editable"
                        :autoSave=true
                        :required="false"
                        :value="text"
                        :text="text"
                        @valueChange="onCellChange(record.key, 'unitPrice', $event)"/>
            </template>

            <!--                        价税合计 iSum-->
            <template slot="iSum" slot-scope="text, record">
                <editable-cell
                        :ref="`iSum_${record.key}`"
                        :defaultEditable="record.editable"
                        :autoSave=true
                        :required="false"
                        :value="text"
                        :text="text"
                        @valueChange="onCellChange(record.key, 'iSum', $event)"/>
            </template>

            <!--            交付日期 deliveries-->
            <template slot="deliveries" slot-scope="text, record">
                <editable-cell
                        :ref="`deliveries_${record.key}`"
                        formType="datePicker"
                        :defaultEditable="record.editable"
                        :required="true"
                        placeholder='请输入日期'
                        :value=null
                        :text="text"/>
            </template>
            <!--            备注 notes-->
            <!--                        价税合计 iSum-->
            <template slot="notes" slot-scope="text, record">
                <editable-cell
                        :ref="`notes_${record.key}`"
                        :defaultEditable="record.editable"
                        :autoSave=true
                        :required="false"
                        :value="text"
                        :text="text"
                        @valueChange="onCellChange(record.key, 'notes', $event)"/>
            </template>


            <template slot="operation" slot-scope="text, record">
                <div class='editable-row-operations'>
                    <span v-if="record.editable">
                        <a @click="() => edit(record.key)">编辑</a>
                        <a @click="() => save(record.key)">保存</a>
                        <a-divider type="vertical"/>
                    </span>
                    <span v-else>
                        <a @click="() => save(record.key)">保存</a>
                        <a @click="() => edit(record.key)">编辑</a>
                    </span>
                </div>
            </template>

        </a-table>

<!--        <a-button type="primary" @click="handleSave">提交</a-button>-->
<!--        <ul>-->
<!--            <li>当前行数据：-->
<!--                <pre>{{JSON.stringify(signData,null,2)}}</pre>-->
<!--            </li>-->
<!--            <li>批量多行数据：-->
<!--                <pre>{{JSON.stringify(mulData,null,2)}}</pre>-->
<!--            </li>-->
<!--        </ul>-->
    </div>
</template>
<script>
    import EditableCell from '@/components/EditableCell/cell.vue';
    import moment from 'moment';

    /*
    * EditableCell Code https://github.com/vueComponent/ant-design-vue/blob/master/components/table/demo/EditableCell.vue
    */
    export default {
        components: {
            EditableCell,
        },
        data() {
            return {
                signData: [],
                mulData: [],
                dateFormat: 'YYYY-MM-DD',
                dataSource: [
                    {
                        key: '1',
                    },
                    {
                        key: '2',
                    }
                ],
                count: 3,
                columns: [
                    {
                        dataIndex: 'test',
                        width: 80,
                        scopedSlots: {customRender: 'test'},
                    },
                    {
                        title: '序号',
                        dataIndex: 'key',
                        width: 70,
                    },
                    {
                        title: '物品编号',
                        dataIndex: 'itemNumber',
                        width: 150,
                        scopedSlots: {customRender: 'itemNumber'},
                    },
                    {
                        title: '物品名称',
                        dataIndex: 'itemName',
                        width: 150,
                        scopedSlots: {customRender: 'itemName'},
                    },
                    {
                        title: '规格型号',
                        dataIndex: 'model',
                        width: 150,
                        scopedSlots: {customRender: 'model'},
                    },
                    {
                        title: '单位',
                        dataIndex: 'unit',
                        width: 150,
                        scopedSlots: {customRender: 'unit'},
                    },
                    {
                        title: '采购数量',
                        dataIndex: 'amount',
                        width: 150,
                        scopedSlots: {customRender: 'amount'},
                    },
                    {
                        title: '含税单价',
                        dataIndex: 'unitPrice',
                        width: 150,
                        scopedSlots: {customRender: 'unitPrice'},
                    },
                    {
                        title: '价税合计',
                        dataIndex: 'iSum',
                        width: 150,
                        scopedSlots: {customRender: 'iSum'},
                    },
                    {
                        title: '上游订单',
                        dataIndex: 'upper',
                        width: 150,
                    },
                    {
                        title: '交付日期',
                        dataIndex: 'deliveries',
                        width: 200,
                        scopedSlots: {customRender: 'deliveries'},
                    },
                    {
                        title: '备注',
                        dataIndex: 'notes',
                        width: 150,
                        scopedSlots: {customRender: 'notes'},
                    },
                    // {
                    //     title: 'operation',
                    //     dataIndex: 'operation',
                    //     width: '150',
                    //     scopedSlots: {customRender: 'operation'},
                    // }
                ],
                fields: ['itemNumber', 'itemName', 'model', 'unit', 'amount', 'unitPrice', 'iSum', 'deliveries'],
                rules: {
                    itemName: {
                        rules: [{
                            required: true,
                            message: '物品名称必填',
                        }]
                    },
                },
            };
        },
        methods: {
            moment,
            // input Change事件
            onCellChange(key, dataIndex, value) {
                console.log(`${dataIndex}：${value} `);
                const dataSource = [...this.dataSource];
                const target = dataSource.find(item => item.key === key);
                if (target) {
                    target[dataIndex] = value;
                    this.dataSource = dataSource;
                }
            },
            // 删除
            onDelete(key) {
                // 拷贝数组数据
                const dataSource = [...this.dataSource];
                // 过滤移除当前项目
                this.dataSource = dataSource.filter(item => item.key !== key);
            },
            // 点击编辑
            edit(key) {
                const newData = [...this.dataSource];
                const target = newData.filter(item => key === item.key)[0];
                if (target) {
                    target.editable = true;
                    this.dataSource = newData;
                }
            },
            // 点击保存
            save(key) {
                this.validateRow(key, this.fields, (err, values) => {
                    if (!err) {
                        // values.deliveries = values.deliveries.format('YYYY-MM-DD');
                        const newData = [...this.dataSource];
                        const row = newData.find(item => key === item.key);
                        if (row) {
                            // 用户数据合并到原对象上
                            Object.assign(row, values);
                            console.log(row.editable)
                            delete row.editable;
                            this.signData = row;
                            console.log('单行保存row', row);
                            // target 保存了最新行数据，可以提价到后台
                            this.dataSource = newData;
                        }
                    }
                });
            },
            // 点击取消
            cancel(key) {
                const newData = [...this.dataSource];
                const target = newData.filter(item => key === item.key)[0];
                if (target) {
                    delete target.editable;
                    this.dataSource = newData;
                }
            },
            // validateRow可以提取为公共函数
            validateRow(key, fields, callback) {
                // 查找验证是否通过
                const row = {};
                let err = false;
                // forEach 对每一个验证，可以更改为some满足一个就提醒
                fields.forEach(filed => {
                    let refName = `${filed}_${key}`;
                    let result = this.$refs[refName].validate();
                    row[filed] = result.value;
                    if (!result.success) {
                        err = true;
                    }
                });
                callback(err, row);
            },
            // 批量提交保存数据
            handleSave() {
                const newData = [...this.dataSource];
                // 找出处于可编辑行
                // const rows = newData.filter(row => {
                //     return row.editable;
                // });
                const rows = newData
                let count = 0;
                // 一个个校验行
                rows.forEach(row => {
                    this.validateRow(row.key, this.fields, (err, values) => {
                        if (!err) {
                            // values.deliveries = values.deliveries.format('YYYY-MM-DD');
                            // 行记录数据合并到row中
                            Object.assign(row, values);
                            count++;
                        }
                    });
                });
                // 最终数据在rows中;
                if (rows.length === count) {
                    // 数据在rows,提交数据
                    this.mulData = rows;
                    // console.log('批量多行rows', rows);
                    console.log(rows)
                }
            },
            // 点击提交
            handleAdd() {
                const {count, dataSource} = this;
                const newData = {
                    key: count,
                    //itemNumber: '',
                    //itemName: '',
                    // model: '',
                    unit: '',
                    // deliveries:moment().format('YYYY-MM-DD'),
                };
                this.dataSource = [...dataSource, newData];
                this.count = count + 1;
            },
        },
    };
</script>
<style scoped>
    .editable-row-operations a {
        margin-right: 8px;
    }

    li {
        text-align: left;
    }

    pre {
        padding: 10px;
        background-color: rgba(0, 0, 0, 0.65);
        color: #ccc;
    }
</style>

